package fr.cephb.joperon.swing;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JMenu;

import javax.swing.AbstractAction;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;


import fr.cephb.joperon.core.db.PrjMgrDB;
import fr.cephb.joperon.core.entities.PrjMgr;
import fr.cephb.swing.ActionSaveTableAs;
import fr.cephb.swing.GenericTableModel;


public class PrjMgrFrame extends  OperonFrame
	{
	private static final long serialVersionUID = 1L;

	private static class Model
		extends GenericTableModel<PrjMgr>
		{
		private static final long serialVersionUID = 1L;
		@Override
		public int getColumnCount() {
			return 4;
			}
		
		@Override
		public String getColumnName(int columnIndex) {
			switch(columnIndex)
				{
				case 0: return "Project-ID";
				case 1: return "Date";
				case 2: return "Author";
				case 3: return "Description";
				}
			return null;
			}
		
		@Override
		public Object getValueOf(PrjMgr item, int columnIndex) {
			switch(columnIndex)
				{
				case 0: return item.getPid();
				case 1: return item.getYmd();
				case 2: return item.getLog();
				case 3: return item.getDef();
				}
			return null;
			}
		}

	private Model tableModel;
	private JTable table;

	public PrjMgrFrame(OperonGUI operon)
		{
		super(operon,"Projects");
		
		AbstractAction action= new AbstractAction("Projects Inputs")
			{
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e)
				{
				select();
				}
			};

		JMenu menu= new JMenu("Action");
		menu.add(action);
		getJMenuBar().add(menu);
		
		this.tableModel= new Model();
		this.table= new JTable(this.tableModel);
		
		getJMenuBar().getMenu(0).add(new ActionSaveTableAs(this,table));
		
		super.content.add(new JScrollPane(this.table),BorderLayout.CENTER);
		
		this.addInternalFrameListener(new InternalFrameAdapter()
			{
			@Override
			public void internalFrameOpened(InternalFrameEvent e) {
				reloadContent();
				}
			});
		
		this.table.addMouseListener(new MouseAdapter()
			{
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount()<2) return;
				select();
				}
			});
		
		selectionListen(action,this.table);
		}
	
	private void select()
		{
		int i=table.getSelectedRow();
		i= table.convertRowIndexToModel(i);
		if(i==-1) return;
		PrjMgr object= tableModel.elementAt(i);
		PrjFinFrame f= new PrjFinFrame(getOperonGUI(),object);
		getDesktopPane().add(f);
		f.setVisible(true);
		}
	

	public void reloadContent()
		{
		PrjMgrDB db=null;
		try {
			db = new PrjMgrDB(getOperon());
			db.open();
			this.tableModel.removeAll();
			this.tableModel.addAll(db.getValues());
			} 
		catch (Exception e)
			{
			e.printStackTrace();
			}
		finally
			{
			safeClose(db);
			}
		
		}
	
	}
